package com.zgs.mall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import com.zgs.common.utils.R;
import com.zgs.mall.ware.entity.WareOrderTaskDetailEntity;
import com.zgs.mall.ware.entity.WareOrderTaskEntity;
import com.zgs.mall.ware.feign.OrderFeignService;
import com.zgs.mall.ware.service.WareOrderTaskDetailService;
import com.zgs.mall.ware.service.WareOrderTaskService;
import com.zgs.mall.ware.vo.*;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zgs.common.utils.PageUtils;
import com.zgs.common.utils.Query;

import com.zgs.mall.ware.dao.WareSkuDao;
import com.zgs.mall.ware.entity.WareSkuEntity;
import com.zgs.mall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@RabbitListener(queues = "stock.release.stock.queue")
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    WareOrderTaskService wareOrderTaskService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderFeignService orderFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuHasStockVo> getSkuhasStock(List<Long> skuIds) {
       return skuIds.stream().map(skuId->{
           Long conut= baseMapper.getSkuhasStock(skuId);
            SkuHasStockVo vo =new SkuHasStockVo();
            vo.setSkuId(skuId);
            vo.setHasStock(conut>0);
            return vo;
        }).collect(Collectors.toList());
    }
    //锁库存
    /**
     * 锁库存：
     *  下单成功 订单过期或取消
     *   订单没成功
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        String orderSn = vo.getOrderSn();
        /**
         * 保存工作库存单详情
         * 为了追溯
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(orderSn);
        wareOrderTaskService.save(taskEntity);
        //找到所有仓库
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            Integer count = item.getCount();
            Long skuId = item.getSkuId();
            SkuWareHasStock stock = new SkuWareHasStock();
            stock.setNum(count);
            stock.setSkuId(skuId);
            List<Long> ids =  this.baseMapper.listWareIdHasStock(skuId);
            stock.setWareIds(ids);
            return stock;
        }).collect(Collectors.toList());
        boolean wareAll=false;
        for (SkuWareHasStock stock : collect) {
            Integer num = stock.getNum();
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareIds();
            //一个商品没有库存就抛出异常
            if (wareIds==null || wareIds.size()==0){
                throw  new RuntimeException();
            }
           boolean ware=false;
            //更新库存
            /**
             * Mq消息发送
             * 1.如果每个商品都锁定成功 将当前商品锁定了几件的工作单记录发送给mq
             * 2.锁定失败，回滚，mq发出去也没事
             */
            for (Long wareId : wareIds) {
                long count=this.baseMapper.warelock(wareId,num);
                if (count>0){
                    ware=true;
                    // 告诉Mq库存锁定成功
                    WareOrderTaskDetailEntity detailEntity=new WareOrderTaskDetailEntity();
                    detailEntity.setSkuId(skuId);
                    detailEntity.setSkuNum(num);
                    detailEntity.setLockStatus(1);
                    detailEntity.setWareId(wareId);
                    detailEntity.setTaskId(taskEntity.getId());
                    wareOrderTaskDetailService.save(detailEntity);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",detailEntity);
                    break;
                }
            }
            if (!ware){
                throw  new RuntimeException();
            }
        }
        
        return null;
    }

    /**
     * 接收Mq消息
     * 释放库存
     * @param channel
     * @param detailEntity
     */
    @Transactional
    @RabbitHandler
    public void releaseLockStock(Message message,Channel channel, WareOrderTaskDetailEntity detailEntity) throws IOException {
        Long wareId = detailEntity.getWareId();
        Long id = detailEntity.getId();
        Integer skuNum = detailEntity.getSkuNum();
        Long skuId = detailEntity.getSkuId();
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(id);
        Long taskId = detailEntity.getTaskId();
       
        if (byId !=null){//存在说明库存扣减成功
            WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(taskId);
            String orderSn = orderTaskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode()==0){
                //库存扣减条件
                //1订单被取消 2订单没下成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {});
                if (data==null || data.getStatus()==4){
                    Integer taskStatus = orderTaskEntity.getTaskStatus();
                    if (taskStatus==1){
                        unlockStock(skuId,wareId,skuNum);
                    }
                }
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }else{
                //扣减失败手动拒绝，并放回队列，让别人继续消费
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
                throw  new RuntimeException("远程服务失败");
            }
        }else{
            //无需解锁
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }

    }

    private void unlockStock(Long skuId, Long wareId, Integer skuNum) {
        this.baseMapper.unlockStock(skuId,wareId,skuNum);
    }

    /**
     * 所有商品的库存
     */
    @Data
    class SkuWareHasStock{
        private Long skuId;
        private List<Long> wareIds;
        private Integer num;
    }
}